import { defineStore } from 'pinia'

type Food = {
  Id: number
  FoodName: string
  FoodImage: string
  Count: number
}

type CartState = {
  FoodCart: Food[]
}

export const useCartStore = defineStore('cart', {
  state: (): CartState => ({
    FoodCart: []
  }),
  getters: {
    getFoodCart: (state) => state.FoodCart
  },
  actions: {
    // 传入id获取数量
    getCountById(id: number) {
      const food = this.FoodCart.find((food) => food.Id === id)
      return food?.Count || 0
    },
    // 添加到购物车
    addToCart(food: Food) {
      this.FoodCart.push(food)
    },
    // 减少数量,减少到0自动删除
    reduceCount(food: Food) {
      food.Count--
      if (food.Count === 0) {
        this.FoodCart = this.FoodCart.filter((item) => item.Id !== food.Id)
      }
    },
    // 清空购物车
    clearCart() {
      this.FoodCart = []
    }
  }
})
